/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 ****************************************************************************/
package com.ijoyplay.tetris;

import com.openfeint.api.OpenFeint;
import com.openfeint.api.OpenFeintDelegate;
import com.openfeint.api.OpenFeintSettings;
import com.openfeint.api.resource.Achievement;
import com.openfeint.api.resource.Leaderboard;
import com.openfeint.api.resource.Score;
import com.openfeint.api.ui.Dashboard;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.NotificationType;
import com.umeng.fb.UMFeedbackService;
import com.umeng.update.UmengUpdateAgent;

import net.youmi.android.AdManager;
import net.youmi.android.AdView;

import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxEditText;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.widget.FrameLayout;

import java.util.List;

public class TetrisAndroid extends Cocos2dxActivity {
    private static Activity ctx;

    private Cocos2dxGLSurfaceView mGLView;

    public static List achievements = null;
    public static List leaderboards = null;

    protected static final int showLeaderBoardsHandler = 0x101;
    protected static final int showAchievementsHandler = 0x102;
    protected static final int showDashBoardsHandler = 0x103;
    protected static final int submitScoresHandler = 0x104;
    protected static final int submitEggsHandler = 0x105;
    protected static final int unlockAchievementsHandler = 0x106;
    protected static final int openURLHandler = 0x107;

    private static final String YOUMI_APP_ID = "da1047f6d0bbf1dc";
    private static final String YOUMI_APP_KEY = "a41cd410012767cc";

    private static final int GET_YOUMI_TIME = 30;// 单位是秒

    private static AdView adView;// 广告的界面句柄

    private static final int IS_VISIBLE = 1;

    // sprivate static Handler OFHandler;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ctx = this;
        MobclickAgent.onError(this);
        UMFeedbackService.enableNewReplyNotification(this, NotificationType.AlertDialog);
        UmengUpdateAgent.update(this);
        initOpenfeint();
        // get the packageName,it's used to set the resource path
        String packageName = getApplication().getPackageName();
        super.setPackageName(packageName);
        // 广告嵌入
        AdManager.init(this, YOUMI_APP_ID, YOUMI_APP_KEY, GET_YOUMI_TIME, true);

        setContentView(R.layout.tetris_demo);

        // 初始化广告视图
        adView = new AdView(this);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        // 设置广告出现的位置(悬浮于屏幕右下角)
        params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        // 将广告视图加入Activity 中
        addContentView(adView, params);

        mGLView = (Cocos2dxGLSurfaceView) findViewById(R.id.tetris_gl_surfaceview);
        mGLView.setTextField((Cocos2dxEditText) findViewById(R.id.textField));

    }

    private void initOpenfeint() {
        OpenFeintSettings settings = new OpenFeintSettings(TetrisApplication.gameName,
                TetrisApplication.gameKey, TetrisApplication.gameSecret, TetrisApplication.gameID);
        OpenFeint.initialize(this, settings, new OpenFeintDelegate() {
        });
        Dashboard.open();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        super.onPause();
        mGLView.onPause();
    }

    @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();
        mGLView.onResume();
    }

    private native void init(Object wadk_this);

    private static void showLeaderBoards() {
        Message message = new Message();
        message.what = TetrisAndroid.showLeaderBoardsHandler;
        OFHandler.sendMessage(message);
    }

    private static void showAchievements() {
        Message message = new Message();
        message.what = TetrisAndroid.showAchievementsHandler;
        OFHandler.sendMessage(message);
    }

    private static void showDashBoards() {
        Message message = new Message();
        message.what = TetrisAndroid.showDashBoardsHandler;
        OFHandler.sendMessage(message);
    }

    private static void submitScores(int scores) {
        Message message = new Message();
        message.what = TetrisAndroid.submitScoresHandler;
        message.arg1 = scores;
        OFHandler.sendMessage(message);
    }

    private static void submitEggs(int eggs) {
        Message message = new Message();
        message.what = TetrisAndroid.submitEggsHandler;
        message.arg1 = eggs;
        OFHandler.sendMessage(message);
    }

    private static void unlockAchievements(String achievementid) {
        Message message = new Message();
        message.what = TetrisAndroid.unlockAchievementsHandler;
        message.obj = achievementid;
        OFHandler.sendMessage(message);
    }

    private static void openURL(String url) {
        Message message = new Message();
        message.what = TetrisAndroid.openURLHandler;
        message.obj = url;
        OFHandler.sendMessage(message);
    }

    /**
     * 设置广告是否可见。
     * 
     * @param visible
     *            值是1表示可见
     */
    private static void setAdViewVisible(int visible) {
        if (IS_VISIBLE == visible) {
            adView.setKeepScreenOn(true);
        } else {
            adView.setKeepScreenOn(false);
        }
    }

    private static Handler OFHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case TetrisAndroid.showLeaderBoardsHandler:
                Dashboard.openLeaderboards();
                break;
            case TetrisAndroid.showAchievementsHandler:
                Dashboard.openAchievements();
                break;
            case TetrisAndroid.showDashBoardsHandler:
                Dashboard.open();
                break;
            case TetrisAndroid.submitScoresHandler:
                long scores = msg.arg1;
                Score scoresScore = new Score(scores);
                Leaderboard scoresLeaderboard = new Leaderboard("916963762");
                scoresScore.submitTo(scoresLeaderboard, new Score.SubmitToCB() {
                    @Override
                    public void onSuccess(boolean newHighScore) {
                        ctx.setResult(Activity.RESULT_OK);
                    }

                    @Override
                    public void onFailure(String exceptionMessage) {
                        ctx.setResult(Activity.RESULT_CANCELED);
                    }
                });
                break;
            case TetrisAndroid.submitEggsHandler:
                long eggs = msg.arg1;
                Score eggsScore = new Score(eggs);
                Leaderboard eggsLeaderboard = new Leaderboard("abc");
                eggsScore.submitTo(eggsLeaderboard, new Score.SubmitToCB() {
                    @Override
                    public void onSuccess(boolean newHighScore) {
                        ctx.setResult(Activity.RESULT_OK);
                    }

                    @Override
                    public void onFailure(String exceptionMessage) {
                        ctx.setResult(Activity.RESULT_CANCELED);
                    }
                });
                break;
            case TetrisAndroid.unlockAchievementsHandler:
                new Achievement((String) msg.obj).unlock(new Achievement.UnlockCB() {
                    @Override
                    public void onSuccess(boolean newUnlock) {
                        ctx.setResult(Activity.RESULT_OK);
                    }

                    @Override
                    public void onFailure(String exceptionMessage) {
                        ctx.setResult(Activity.RESULT_CANCELED);
                    }
                });
                break;
            case TetrisAndroid.openURLHandler:
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse((String) msg.obj));
                ctx.startActivity(i);
                break;
            }
            super.handleMessage(msg);
        }
    };

    static {
        System.loadLibrary("cocosdenshion");
        System.loadLibrary("tetris");
    }
}
